package com.bigknow.appstore.proxy.handler.init;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 将client channel注册入channel管理容器
 * Created by chaos on 2016/6/2.
 */
@ChannelHandler.Sharable
public class ChannelRegisterHandler extends ChannelInboundHandlerAdapter {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private ChannelGroup allChannels;

    public ChannelRegisterHandler(ChannelGroup allChannels){
        this.allChannels = allChannels;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        allChannels.add(ctx.channel());
        ctx.fireChannelRegistered();
    }

    /**
     * 当channel调用close方法成功后会触发channelInactive方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception{
        logger.info("channel 已经关闭id:[{}]",ctx.channel().id().asLongText());
        allChannels.remove(ctx.channel());
        ctx.fireChannelInactive();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        logger.info("channel连接已经超时或者异常断开，信息：" +cause);
        allChannels.remove(ctx.channel());
    }
}
